﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace Spider
{
    class TimingRun
    {
        string filename;
        int timeInterval;
        int processId = -1;

        Thread newThread = null;
        public void Start()
        {
            filename = Spider.Properties.Settings.Default.TimeRunFileName;
            if (!System.IO.File.Exists(filename))
                return;
            timeInterval = Spider.Properties.Settings.Default.TimeRunInterval;
            newThread = new Thread(Run);
            newThread.Start();
        }

        public void Stop()
        {
            if (newThread != null)
            {
                if (newThread.ThreadState == System.Threading.ThreadState.Running || newThread.ThreadState == System.Threading.ThreadState.WaitSleepJoin)
                    newThread.Abort();
            }
        }

        void Run()
        {
            while (true)
            {
                StartProcess();
                Thread.Sleep(timeInterval * 60 * 1000);
                KillProcess();
                Thread.Sleep(5 * 1000);
            }
        }

        void StartProcess()
        {
            Process p = new Process();
            p.StartInfo.FileName = filename;
            p.Start();
            processId = p.Id;
            Console.WriteLine("The Process have been started.    DateTime:{0}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
        }

        void KillProcess()
        {
            try
            {
                Process runProcess = Process.GetProcessById(processId);
                if (runProcess != null)
                {
                    runProcess.Kill();
                    Console.WriteLine("The Process have been Killed.    DateTime:{0}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
                }
                else
                    Console.WriteLine("The Process have been killed by other user.    DateTime:{0}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));

            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}
